import React, { Component, Fragment } from 'react';
import { Button, Breadcrumb, Checkbox, Modal, Form, Input, message, Tooltip, 
	Transfer, ConfigProvider, Select, Dropdown, Menu, Radio,Empty } from 'antd';
import { AppstoreOutlined, MenuOutlined, ExclamationCircleOutlined, DownOutlined,
	UsergroupAddOutlined, UsergroupDeleteOutlined, UserSwitchOutlined, UserDeleteOutlined
 } from '@ant-design/icons';
import zh_CN from 'antd/lib/locale-provider/zh_CN'
import axios from './../../axios';
import FileList from './../../components/FileList';
import FileListThumb from './../../components/FileListThumb';
import ShareTree from './../../components/shareTree';
import boy1 from './../../statics/shareicon/boy1.png';
import boy2 from './../../statics/shareicon/boy2.png';
import boy3 from './../../statics/shareicon/boy3.png';
import girl1 from './../../statics/shareicon/girl1.png';
import girl2 from './../../statics/shareicon/girl2.png';
import girl3 from './../../statics/shareicon/girl3.png';
import { connect } from 'react-redux';
// import ContextMenu from './../../components/ContextMenu';
import Utils from './../../utils/utils';
import './index.less';

const Option = Select.Option;
class ShareWhole extends Component {
	
	formRef = React.createRef();//创建共享群表单
	
	constructor(props){
		super(props);
		this.state = {
			isCreateVisible: false,//创建共享群模态框
			fileList: "",//共享群文件列表
			shareTotal: 0,//共享群个数
			groupid: "",//当前点击的群id
			groupname: "",//当前点击的群名称
			is_admin: 0,//当前是否是群主,1->是，0->不是
			res: false,
			//进入共享群后
			pid: 0,//当前所在目录层级
			filelist: [],//文件列表
			checkedArr: [],//选中项
			showCheckboxAll: false,//全选checkbox框
			view_mode: "list",//列表显示或矩阵显示
			isCreateFolder: false,//新建文件夹状态
			isShareGroupVisible: false,//加入到共享群的模态框
			dirCheckedId: "",//选中的网盘文件id，将来导入到共享群
			mockData: [],//网盘项目所有用户
			targetKeys: [],//在群内的用户
			isHandover: false,//移交群主模态框
			userOptions: null,//在群内的用户，移交群主模态框使用到
			handoverUser: "",//移交群主的id
			groupUserlistBefore: "",//顶部显示的群用户
			groupUserlist: "",//顶部显示的群用户鼠标移入显示群内所有用户
		};
	}
	
	componentWillUnmount(){
		sessionStorage.clear();//关闭页面清除缓存
	}
	
	componentDidMount(){
		
		//判断是否点击过群名称，有就显示文件列表页，否则显示群列表页面
		const groupid = sessionStorage.getItem("groupid");
		if(groupid){
			//获取群内文件列表
			this.requestList();
			this.getUser(groupid);
		}else{
			//获取共享群列表
			this.requestShareList();
		}
		
		this.getAllUser();//获取所有网盘用户
		
		//群内文件显示方式
		const view_mode = localStorage.getItem("jqmkj_sharegroup_view_mode");
		
		if(view_mode){
			this.setState({view_mode});
		}
	}
	
	//刷新数据
	refreshList = () => {
		//判断是否点击过群名称，有就显示文件列表页，否则显示群列表页面
		const groupid = sessionStorage.getItem("groupid");
		setTimeout(()=>{
			if(groupid){
				//获取群内文件列表
				this.requestList();
				this.getUser(groupid);
			}else{
				//获取共享群列表
				this.requestShareList();
			}
		}, 1000);
	}
	
	//获取共享群列表
	requestShareList = () => {
		axios.get({
			url:"/files/group/list",
			params: {page: 1, pageSize: 1000}
		})
		.then(res => {
			if(res.code === 0){
				let fileList = this.renderFileList(res.result.list);
				this.setState({fileList, shareTotal: res.result.total})
			}
		})
	}
	
	//获取所有网盘用户
	getAllUser = () => {
		//获取网盘所有用户
		axios.get({
			url:"/files/group/getUsers"
		}).then(res => {
			if(res.code === 0){
				let mockData = [];
				mockData = res.result.list.map(item => {
					return {
						key: item.id,
						title: item.user_name
					}
				})
				this.setState({ mockData });
			}
		})
	}
	//获取群内成员
	getUser = (groupid) => {
		//获取群内成员
		axios.get({
			url:"/files/group/getUserByGroup",
			params: {groupid}
		}).then(res => {
			if(res.code === 0){
				let targetKeys = [];
				let userOptions = null;
				targetKeys = res.result.map(item => {
					return item.id
				});
				userOptions = res.result.map(item => {
					return <Option value={item.id} key={item.id}>{item.user_name}</Option>
				});
				
				const length = res.result.length;//多少群成员
				let groupUserlist = "";//鼠标移入成员显示的全部群成员
				let groupUserlistBefore ="";//顶部显示的群成员
				for(let val of res.result){
					groupUserlist += val.user_name + "，"
				}
				groupUserlist = "群成员：" + groupUserlist.slice(0, -1);
				if(length === 0){
					groupUserlistBefore = "无群成员";
				}else if(length === 1){
					groupUserlistBefore = res.result[0].user_name + "-1位成员"
				}else if(length === 2){
					groupUserlistBefore = res.result[0].user_name + "与" + res.result[1].user_name + "-2位成员"
				}else if(length === 3){
					groupUserlistBefore = res.result[0].user_name + "，" + res.result[1].user_name + "，" +
					res.result[2].user_name + "-3位成员";
				}else{
					groupUserlistBefore = res.result[0].user_name + "，" + res.result[1].user_name + "，" +
					res.result[2].user_name + "...等共" + length + "位用户";
				}
				this.setState({ targetKeys, userOptions, groupUserlist, groupUserlistBefore });
			}
		})
	}
	
	//创建共享群
	createShareGroup = () => {
		this.setState({isCreateVisible: true});
		setTimeout(() => {
			this.formRef.current.resetFields();
		}, 500);
	}
	
	//创建共享群提交
	handleSubmit = (values) => {
		this.setState({isCreateVisible: false})
		axios.ajax({
			url:"/files/group/create",
			method: "post",
			data: values
		})
		.then(res => {
			if(res.code === 0){
				message.success("创建成功");
				this.requestShareList();//重新获取数据
			}
		})
	}
	
	//遍历共享群列表数据
	renderFileList(data){
		const getIconUrl = (state) => {
			return {
				'boy1': boy1,
				'boy2': boy2,
				'boy3': boy3,
				'girl1': girl1,
				'girl2': girl2,
				'girl3': girl3,
				'': boy1
			}[state];
		}
		return data.map((item,index)=>{
			return <li
						key={index}
						className="act line-sharegroup"
						onClick={()=>this.lineClick(item.id,item.name,item.is_admin)}
						onContextMenu={()=>this.contextMenu(item.id,item.name)}
				>
					<span className="act w300">
						<img src={getIconUrl(item.icon)} alt="群头像" className="line-sharegroup-icon" />
						<Tooltip placement="bottomLeft" title={item.introduce}>
							{item.name}
						</Tooltip>
					</span>
					<span className="act overflow-text">
						{Utils.formateTime(item.update_time)},{item.dynamic}
					</span>
			</li>
		})
	}
	
	//点击行，进入群详细信息
	lineClick = (id, name, is_admin) => {
		sessionStorage.setItem("groupid", id);
		sessionStorage.setItem("fileid", 0);
		sessionStorage.setItem("is_admin", is_admin);
		let breadcrumbArr = [{fileid: 0, filename: name}];
		sessionStorage.setItem("breadcrumb", JSON.stringify(breadcrumbArr));
		this.requestList();//获取群内文件
		this.setState({groupid: id, groupname: name, is_admin});
		this.getUser(id);//获取群内成员
	}
	
	//点击【共享群】
	allShareGroup = () => {
		this.requestShareList();
		this.setState({groupid: "", fileid: 0});
		//还原一下
		sessionStorage.setItem("groupid", "");
		sessionStorage.setItem("fileid", 0);
	}
	
	//在共享群行上右击
	contextMenu = (id, name) => {
		this.getUser(id);//获取群内成员
		this.setState({groupid: id, groupname: name});
	}
	
	//群上右击某一项
	contextMenuClick = (type) => {
		switch (type){
			case "addUser": this.addUser(); break;
			case "deleteUser": this.deleteUser(); break;
			case "handover": this.handover(); break;
			case "quitGroup": this.quitGroup(); break;
			default: break;
		}
	}
	
	//邀请用户进群
	addUser = () => {
		this.setState({isUserVisible: true});
	}
	
	//踢人出群
	deleteUser = () => {
		this.setState({isUserVisible: true});
	}
	
	//移交群主
	handover = () => {
		this.setState({isHandover: true});
	}
	
	//退群
	quitGroup = () => {
		let { groupid, groupname } = this.state;
		if(!groupid){
			groupid = sessionStorage.getItem("groupid");
		}
		Modal.confirm({
			title: `请您确认？`,
			icon: <ExclamationCircleOutlined />,
			content: `确认退出 ${groupname} ?`,
			okText: "确认",
			cancelText: "取消",
			onOk:()=>{
				axios.ajax({
					url: "/files/group/quit", 
					method: "post",
					data: { groupid }
				}).then(res=>{
					if(res.code === 0){
						message.success("退出成功")
						this.refreshList();
					}else{
						
					}
				})
			}
		})
	}
	
	
	
	
	//以下为文件列表页内容
	
	//进入群后的文件列表切换列表显示或矩阵显示
	changeViewMode = (view_mode) => {
		this.setState({view_mode});
		localStorage.setItem("jqmkj_sharegroup_view_mode", view_mode);
	}
	
	//获取文件列表
	requestList = () => {
		let fileid = sessionStorage.getItem("fileid");
		let groupid = sessionStorage.getItem("groupid");
		let breadcrumbArr = JSON.parse(sessionStorage.getItem("breadcrumb"));
		if(breadcrumbArr){
			let breadcrumbList = breadcrumbArr.map(item => {
				return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
			})
			this.setState({breadcrumbList});
		}else{
			breadcrumbArr = [{fileid: 0, filename: this.state.groupname}];
			let breadcrumbList = breadcrumbArr.map(item => {
				return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
			})
			this.setState({breadcrumbList});
		}
		axios.get({
			url: "/share/group/list", 
			method: "get",
			params: {pid: fileid, groupid: groupid},
		}).then(res=>{
			if(res.code === 0 && res.result.list){
				let resData = res.result.list.map((item, index)=>{
					let checked = false;
					return {...item, checked}
				})
				this.setState({
					filelist: resData,
					count: res.result.pagination.count,
					checkedArr: [],
					res: true
				})
			}
		}).catch(err=>{
		})
	}
	
	//点击进入文件夹
	folderClick = (fileid, filename) => {
		
		let breadcrumbArr = JSON.parse(sessionStorage.getItem("breadcrumb"));

		let flag = false;
		for(let i = 0; i < breadcrumbArr.length; i++){
			if(breadcrumbArr[i].fileid === fileid){
				breadcrumbArr = breadcrumbArr.slice(0,i+1);
				flag = true;
			}
		}
		if(!flag){
			breadcrumbArr.push({fileid,filename});
		}
		sessionStorage.setItem("breadcrumb", JSON.stringify(breadcrumbArr));
		let breadcrumbList = breadcrumbArr.map(item => {
			return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
		})
		this.setState({breadcrumbList})
		sessionStorage.setItem("fileid", fileid);
		this.requestList();
	}
	
	checkedClick = (checkedArr) => {
		this.setState({
			checkedArr
		})
	}
	
	//点击全选checkbox框
	clickCheckboxAll = e => {
		this.props.checkboxAll(e.target.checked);
	}
	
	//导入网盘文件
	dirChecked = (fileid) => {
		this.setState({dirCheckedId: fileid});
	}
	
	//导入网盘文件提交
	dirCheckedSubmit = () => {
		const fileid = this.state.dirCheckedId;
		const groupid = sessionStorage.getItem("groupid");
		if(!fileid){
			message.info("请先选择一个文件");
		}else{
			this.setState({isShareGroupVisible: false});
			axios.get({
				url: "/share/group/share", 
				params: { fileid, groupid }
			}).then(res=>{
				if(res.code === 0){
					message.success("加入共享群成功");
					this.refreshList();//刷新列表
				}else{
					
				}
			})
		}
	}
	
	//群成员管理，符合筛选条件返回true
	filterOption = (inputValue, option) => {
		return option.title.indexOf(inputValue) > -1;
	}
	
	//群成员管理，穿梭框变化时
	handleUserChange = (targetKeys) => {
		//beforeTargetKeys表示上一次的群成员，targetKeys表示操作后的群成员
		let beforeTargetKeys = this.state.targetKeys;
		//取出两个数组的不同
		function getArrDifference(arr1, arr2) {
			return arr1.concat(arr2).filter(function(v, i, arr) {
				return arr.indexOf(v) === arr.lastIndexOf(v);
			});
		}
		let userIdArr = getArrDifference(beforeTargetKeys, targetKeys);
		let groupid = this.state.groupid;
		if(!groupid){
			groupid = sessionStorage.getItem("groupid");
		}
		if(beforeTargetKeys.length > targetKeys.length){
			//移除成员（踢人出群）
			for(let val of userIdArr){
				axios.ajax({
					url: "/files/group/delUser", 
					method: "post",
					data: { userid: val, groupid }
				}).then(res=>{
					if(res.code === 0){
					}else{
					}
				})
			}
		}else{
			//增加成员（邀请加入成员
			for(let val of userIdArr){
				axios.ajax({
					url: "/files/group/pullUser", 
					method: "post",
					data: { userid: val, groupid }
				}).then(res=>{
					if(res.code === 0){
					}else{
					}
				})
			}
		}
		message.success("操作成功");
		this.setState({targetKeys});
		
		//操作完后刷新列表
		this.refreshList();
	}
	
	//移交群主选择时
	handoverChange = value => {
		this.setState({handoverUser: value});
	}
	
	//移交群主提交
	handoverSubmit = () => {
		this.setState({isHandover: false});
		const userid = this.state.handoverUser;
		let groupid = this.state.groupid;
		if(!groupid){
			groupid = sessionStorage.getItem("groupid");
		}
		if(!userid){
			Modal.warning({
				title: '提示',
				content: '请选择一个用户作为群主',
			});
		}else{
			axios.ajax({
				url: "/files/group/handover", 
				method: "post",
				data: { userid, groupid }
			}).then(res=>{
				if(res.code === 0){
					message.success("移交成功");
					this.refreshList();
				}else{
					message.error("移交失败")
				}
			})
		}
	}
	
	render(){
		const layout = {
		    labelCol: { span: 4 },
		    wrapperCol: { span: 20 },
		};
		const tailLayout = {
		    wrapperCol: { offset: 4, span: 20 },
		};
		const hasSelectedLength = this.state.checkedArr.length;
		const { showCheckboxAll, isShareGroupVisible, isUserVisible, mockData, targetKeys, 
		isHandover, userOptions, groupUserlist, groupUserlistBefore } = this.state;
		const hasgroupid = sessionStorage.getItem("groupid");
		const menu = (
			<Menu>
				<Menu.Item key="1" onClick={this.addUser} ><UsergroupAddOutlined />拉人进群</Menu.Item>
				<Menu.Item key="2" onClick={this.deleteUser} ><UsergroupDeleteOutlined />踢人出群</Menu.Item>
				<Menu.Item key="3" onClick={this.handover} ><UserSwitchOutlined />移交群主</Menu.Item>
				<Menu.Item key="4" onClick={this.quitGroup} ><UserDeleteOutlined />退&#x3000;&#x3000;群</Menu.Item>
		    </Menu>
		);
		const is_admin = parseInt(sessionStorage.getItem("is_admin"));
		return (
			<Fragment>
			{ !hasgroupid ?
				<div style={{height: '100%'}}>
					<div className="page-header">
						<Button
							type="primary"
							onClick={this.createShareGroup}
						>创建共享群</Button>
					</div>
					<div className="page-content">
						{this.state.shareTotal > 0 ?
							<div>
								<div className="breadcrumb">
									<span className="share-allname text-bold" onClick={this.allShareGroup}>共享群</span>
								</div>
								<div className="line-header">
									<div className="border-bottom">
										<span className="w300">群名称</span>
										<span>最近动态</span>
									</div>
								</div>
								<ul>
									{this.state.fileList}
								</ul>
								{/*<ContextMenu contextMenuType="sharegroup" contextMenu={this.contextMenuClick} />*/}
							</div>
							:
							<div className="empty-page">
								<div>
									<Empty description='暂无群组,点击左上角创建一个把'/>
									{/*
									<img src={emptyicon} alt="空" />
									<p>暂无群组,点击左上角创建一个把</p>
									*/}
								</div>
							</div>
						}
					</div>
					
				</div>
				:
				<div className="page-wrap">
					<div className="page-header">
						<div className="upload-wrap">
							{/*<Button 
								type="primary" 
								onClick={()=>this.setState({isShareGroupVisible: true})}
								style={{marginRight: "10px"}}
							>
								导入网盘文件
							</Button>*/}
							{is_admin === 1 ?
								<Dropdown overlay={ menu }>
									<Button type="primary" ghost>
										群用户管理<DownOutlined />
									</Button>
								</Dropdown>
								:
								<Button onClick={this.quitGroup} type="primary" ghost><UserDeleteOutlined />退群</Button>
							}
							<div className="user-list">
								<Tooltip placement="bottom" title={groupUserlist} type="primary"ghost>
									<span>群成员: {groupUserlistBefore}</span>
								</Tooltip>
							</div>
						</div>
						<div className="change-show">
							{this.state.view_mode === "list" ?
								<AppstoreOutlined
									className={this.state.view_mode === "thumb" ? "active" : ""}
									onClick={()=>this.changeViewMode("thumb")}
								/>
								:
								<MenuOutlined 
									className={this.state.view_mode === "list" ? "active" : ""}
									onClick={()=>this.changeViewMode("list")} 
								/>
							}
						</div>
					</div>
					<div className="page-content">
						<div className="breadcrumb">
							<span className="share-allname" onClick={this.allShareGroup}>共享群&nbsp;>&nbsp;</span>
							<Breadcrumb style={{float: "left"}}>
								{
									this.state.breadcrumbList
								}
							</Breadcrumb>
						</div>
						{ 
							hasSelectedLength > 0 ?
							<div className="selected-num">
								已选择{hasSelectedLength} 项
							</div> : ""
						}
						{
							this.state.filelist.length > 0 ? 
							<div
								className="line-header"
								onMouseEnter={()=>this.setState({showCheckboxAll:true})}
								onMouseLeave={()=>this.setState({showCheckboxAll:false})}
							>
								{   (hasSelectedLength > 0 || showCheckboxAll) ?
									<div className="checkboxall-wrap">
										<Checkbox onClick={(e)=>this.clickCheckboxAll(e)} />
									</div>:""
								}
								<div className="border-bottom">
									<span>文件名</span>
									{this.state.view_mode === "list" ? 
										<Fragment>
											<span className="w200 float-right">上次修改时间</span>
											<span className="w200 float-right">大小</span>
										</Fragment>:""
									}
								</div>
							</div>:""
						}
						{
							this.state.filelist.length > 0 ? 
							<div className="file-wrap">
								{ 
									this.state.view_mode === "list" ? 
									<FileList 
										filelist={this.state.filelist}
										folderClick={this.folderClick}
										refreshList={this.refreshList}
										checkedClick={this.checkedClick}
										contextMenuType="sharegrouplist"
									/>:
									<FileListThumb
										filelist={this.state.filelist}
										folderClick={this.folderClick}
										refreshList={this.refreshList}
										checkedClick={this.checkedClick}
										contextMenuType="sharegrouplist"
									/>
								}
								<p style={{textAlign: "center", clear: "both"}}>共{this.state.count}项</p>
							</div>
							:this.state.res?
							<div className="empty-page">
								<div>
								<Empty description='暂无数据'/>
								</div>
							</div>:""
						}
					</div>
				</div>
			}
				<Modal
					visible={isShareGroupVisible}
					title="从微云添加文件"
					okText="确认"
					cancelText="取消"
					onOk={this.dirCheckedSubmit}
					onCancel={()=>this.setState({isShareGroupVisible: false})}
				>
					<ShareTree dirChecked={this.dirChecked} />
				</Modal>
				<Modal
					title="创建共享群"
					visible={this.state.isCreateVisible}
					onCancel={()=>this.setState({isCreateVisible: false})}
					footer={null}
				>
					<Form
						{...layout}
						ref={this.formRef}
						onFinish={this.handleSubmit}
					>
						<Form.Item
							label="群名称"
							name="name"
							rules={[
								{required: true, message: "请输入群名称"},
							]}
						>
							<Input autoComplete="off" />
						</Form.Item>
						<Form.Item
							label="群介绍"
							name="introduce"
							rules={[
								{required: true, message: "请输入群介绍"},
							]}
						>
							<Input.TextArea autoComplete="off" />
						</Form.Item>
						<Form.Item
							label="群头像"
							name="icon"
							rules={[
								{required: true, message: "请选择"},
							]}
						>
							<Radio.Group>
								<Radio value="boy1">
									<img src={boy1} alt="群头像" className="line-sharegroup-icon" />
								</Radio>
								<Radio value="boy2">
									<img src={boy2} alt="群头像" className="line-sharegroup-icon" />
								</Radio>
								<Radio value="boy3">
									<img src={boy3} alt="群头像" className="line-sharegroup-icon" />
								</Radio>
								<Radio value="girl1">
									<img src={girl1} alt="群头像" className="line-sharegroup-icon" />
								</Radio>
								<Radio value="girl2">
									<img src={girl2} alt="群头像" className="line-sharegroup-icon" />
								</Radio>
								<Radio value="girl3">
									<img src={girl3} alt="群头像" className="line-sharegroup-icon" />
								</Radio>
							</Radio.Group>
						</Form.Item>
						<Form.Item  {...tailLayout}>
							<Button type="primary" htmlType="submit">
								保存
							</Button>
							<Button htmlType="button" onClick={()=>this.formRef.current.resetFields()}>
								重置
							</Button>
						</Form.Item>
					</Form>
				</Modal>
				<Modal
					title="群用户管理（左右移动用户完成操作）"
					visible={isUserVisible}
					width={600}
					footer={[
						<Button key="back" onClick={()=>{this.setState({isUserVisible: false})}}>关闭</Button>
					]}
					onCancel={()=>{this.setState({isUserVisible: false})}}
				>
					<ConfigProvider locale={zh_CN}>
						<Transfer
							listStyle={{width: 200,height: 400}}
							titles={["非群成员","群成员"]}
							showSearch
							searchPlaceholder="输入用户名"
							dataSource={mockData}
							filterOption={this.filterOption}
							targetKeys={targetKeys}
							onChange={this.handleUserChange}
							render={item=>item.title}
						/>
					</ConfigProvider>
				</Modal>
				<Modal
					title="移交群主"
					visible={isHandover}
					onCancel={()=>{this.setState({isHandover: false})}}
					okText="确认"
					cancelText="取消"
					onOk={this.handoverSubmit}
				>
					<Select
						placeholder="请选择用户作为群主"
						onChange={this.handoverChange}
						style={{width: '100%'}}
					>
						{ userOptions }
					</Select>
				</Modal>
			</Fragment>
		)
	}
}

const mapDispatch = (dispatch) => {
	return {
		checkboxAll(isCheckedAll){
			dispatch({
				type: "CHECKBOX_ALL",
				isCheckedAll
			})
		}
	}
}

export default connect(null, mapDispatch)(ShareWhole);